const tableBody = document.getElementById("table-body")

let flights = [
  {
    time: "08:11",
    destination: "OMAN",
    flight: "OX 203",
    gate: "A 01",
    remarks: "ON TIME",
  },
  {
    time: "12:39",
    destination: "LONDON",
    flight: "CL 320",
    gate: "C 31",
    remarks: "CANCELLED",
  },
  {
    time: "13:21",
    destination: "DUBAI",
    flight: "DXB 201",
    gate: "A 19",
    remarks: "",
  },
  {
    time: "14:01",
    destination: "FRANKFURT",
    flight: "FR 402",
    gate: "B 02",
    remarks: "ON TIME",
  },
  {
    time: "15:22",
    destination: "TOKYO",
    flight: "TK 211",
    gate: "A 32",
    remarks: "DELAYED",
  },
]

let destinations = [
  "BOSTON",
  "CHICAGO",
  "OMAN",
  "LONDON",
  "WASHINGTONG",
  "DUBAI",
  "FRANKFURT",
  "TOKYO",
  "TAIPEI",
  "HONGKONG",
]
let remarks = ["ON TIME", "DELAYED", "CANCELLED"]
let hour = 15

function populateTable() {
  for (const flight of flights) {
    //创建tbody的行
    const tableRow = document.createElement("tr")
    for (const flightDetail in flight) {
      //创建每一行中的每一格
      const tableCell = document.createElement("td")
      const word = Array.from(flight[flightDetail])
      //每格中单词的每个字母占一个div
      for (const [index, letter] of word.entries()) {
        const letterElement = document.createElement("div")
        //产生波浪翻转的效果
        setTimeout(() => {
          letterElement.classList.add("flip")
          letterElement.textContent = letter
          tableCell.append(letterElement)
        }, 100 * index)
      }
      tableRow.append(tableCell)
    }
    tableBody.append(tableRow)
  }
}

populateTable()

function generateLetter() {
  const alphabat = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  return alphabat.charAt(Math.floor(Math.random() * alphabat.length))
}

function generateNumber(maxNumber) {
  const numbers = "0123456789"
  if (maxNumber) {
    const newNumbers = numbers.slice(0, maxNumber + 1)
    return newNumbers.charAt(Math.floor(Math.random() * newNumbers.length))
  }
  return numbers.charAt(Math.floor(Math.random() * numbers.length))
}

function generateTime() {
  let displayHour = hour
  if (hour < 24) {
    hour++
  } else {
    hour = 0
    displayHour = hour
  }
  if (displayHour < 10) {
    displayHour = "0" + displayHour
  }

  return displayHour + ":" + generateNumber(5) + generateNumber()
}

//删除td的第一行 并在最后一行再随机生成一次航班 循环播放
function shuffleUp() {
  flights.shift()
  flights.push({
    time: generateTime(),
    destination: destinations[Math.floor(Math.random() * destinations.length)],
    flight:
      generateLetter() +
      generateLetter() +
      " " +
      generateNumber() +
      generateNumber(),
    gate: generateLetter() + " " + generateNumber() + generateNumber(),
    remarks: remarks[Math.floor(Math.random() * remarks.length)],
  })
  //table清空
  tableBody.textContent = ""
  populateTable()
}

setInterval(shuffleUp, 5000)
